const { Controller } = require('egg')
const fs = require('fs')
const { rand } = require('../utils/rand');
const qiniu = require('qiniu')


class GoodsController extends Controller {
    static TABLE_GOOGDS = 'goods'

    static userMap = [
        {
            key: 'ergou',
            label: '二狗',
            icon: '🐶'
        },
        {
            key: 'xt',
            label: '二狗姐',
            icon: '🍑'
        }
    ]

    async index() {
        await this.ctx.render('goods/index.html', {
            users: JSON.stringify(GoodsController.userMap)
        })
    }
    async dashboard() {
        const { user = null, page = 1, ip = '', brand = '', type = '', character = '' } = this.ctx.query
        if (!user)  {
            this.ctx.redirect('/goods')
            return
        }
        const where = {
            user
        }

        let goodsWhereArr = [
            `user = '${user}'`,
        ]
        
        let filterWhereArr = []
        if (ip && ip !== '') {
            filterWhereArr.push(`(ip in (${ip.split(',').map(v => `'${v}'`).join(',')}))`)
        }
        if (brand && brand !== '') {
            filterWhereArr.push(`(brand in (${brand.split(',').map(v => `'${v}'`).join(',')}))`)
        }
        if (type && type !== '') {
            filterWhereArr.push(`(type in (${type.split(',').map(v => `'${v}'`).join(',')}))`)
        }
        if (character && character !== '') {
            filterWhereArr.push(`(character in (${character.split(',').map(v => `'${v}'`).join(',')}))`)
        }
        if (filterWhereArr.length > 0) {
            goodsWhereArr.push(filterWhereArr.join(' or '))
        }

        const sql = `select * from ${GoodsController.TABLE_GOOGDS} where ${goodsWhereArr.join(' AND ')} limit 10 offset ${(page - 1) * 10};`
        const goods = await this.app.mysql.query(sql)
        const _count = await this.app.mysql.query(`select count(id) as c from ${GoodsController.TABLE_GOOGDS} where ${goodsWhereArr.join(' AND ')};`)
        const count = _count[0]['c']

        const allOptions = await this.app.mysql.select(GoodsController.TABLE_GOOGDS, { where: { user } })
        const ipOptions = allOptions.map(v => v.ip)
        const brandOptions = allOptions.map(v => v.brand)
        const typeOptions = allOptions.map(v => v.type)
        const characterOptions = allOptions.reduce((pre, cur) => {
            return [...pre, ...cur.character.split(',')]
        }, [])

        await this.ctx.render('goods/dashboard.html', {
            user,
            userText: GoodsController.userMap.find(v => v.key === user).label,
            goodsJson: JSON.stringify(goods.map(v => ({
                ...v,
                character: v.character.split(','),
                img: v.img.split(','),
            }))),
            options: JSON.stringify({
                ip: [...new Set(ipOptions)].filter(v => !!v).map(v => ({label: v, value: v})),
                brand: [...new Set(brandOptions)].filter(v => !!v).map(v => ({label: v, value: v})),
                type: [...new Set(typeOptions)].filter(v => !!v).map(v => ({label: v, value: v})),
                character: [...new Set(characterOptions)].filter(v => !!v).map(v => ({label: v, value: v}))
            }),
            count
        })
    }

    async upload() {
        const { ctx } = this

        const files = ctx.request.files
        let filename = [
            rand(100, 999),
            new Date().getTime()
        ].join('-') + '.' + files[0].filename.split('.').at(-1)
        
        const mac = new qiniu.auth.digest.Mac(this.app.config.qiniu.ak, this.app.config.qiniu.sk)
        const options = {
            scope: `xt-image-space:website/goods/${filename}`,
            force: true
        };
        const putPolicy = new qiniu.rs.PutPolicy(options)
        const uploadToken = putPolicy.uploadToken(mac)
        const config = new qiniu.conf.Config()
        
        async function _upload() {
            const formUploader = new qiniu.form_up.FormUploader(config)
            const putExtra = new qiniu.form_up.PutExtra()
            const key = 'website/goods/' + filename
            // 文件上传
            return new Promise((resolve, reject) => {
                formUploader.putFile(uploadToken, key, files[0].filepath, putExtra)
                    .then(({ data, resp }) => {
                        if (resp.statusCode === 200) {
                            resolve({
                                res: 'ok',
                                data
                            });
                        } else {
                            resolve({
                                res: 'err',
                                code: resp.statusCode,
                                data
                            })
                        }
                    })
                    .catch(err => {
                        resolve({
                            res: 'err',
                            err
                        })
                    })
            })
        }

        try {
            const uploadRes = await _upload()

            ctx.body = {
                code: 200,
                msg: '上传完毕',
                data: {
                    res: 'ok',
                    data: uploadRes
                }
            }
        } catch (e) {
            // console.log(e)
            
            ctx.body = {
                code: 500,
                msg: '上传失败',
                data: e
            }
        }
    }
    async save() {
        const { brand = '', character = '', img = '', ip = '', title = '', type = '' } = this.ctx.request.body
    }
}

module.exports = GoodsController
